<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :search.sync="search"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template v-slot:menuLeft>
        <el-button type="success"
                   size="small"
                   plain
                   icon="el-icon-upload2"
                   @click="handleImport">导入
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.info_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template v-slot:default="scope" el-form-itemmenu>
        <el-button link size="small" icon="el-icon-connection" @click.stop="preview(scope.row)" title="预览图片">预览</el-button>
      </template>

    </avue-crud>
    <el-dialog title="文件导入"
               append-to-body
               :visible.sync="uploadBox"
               width="555px">
      <avue-form :option="uploadOption" v-model="uploadForm" :upload-after="uploadAfter"></avue-form>
    </el-dialog>
    <image-viewer append-to-body v-if="enablePreview" :url-list="previewPath" :on-close="closePreview"/>
  </basic-container>
</template>

<script>
  import ImageViewer from "element-plus/dist/index.full.min.js";
  import {ossApi} from "/src/api/system/oss";
  import {baseUrl} from "/src/config/env";
  import {mapState} from "pinia";
  import {useUserStore} from "/src/store/modules/user.js";
  import {avueVaildData} from "../../utils/validate.js";

  export default {
    components: {ImageViewer},
    data() {
      return {
        form: {},
        search:{},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        uploadBox: false,
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          addBtn: false,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "文件名称",
              prop: "name",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "是否图片",
              prop: "isImg",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "文件类型",
              prop: "contentType",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "文件大小",
              prop: "fileSize",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "物理路径",
              prop: "path",
              search: true,
              rules: [{
                required: true,
                message: "请输入物理路径",
                trigger: "blur"
              }]
            },
            {
              label: "访问路径",
              prop: "url",
              search: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "来源",
              prop: "source",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "创建时间",
              prop: "createTime",
              type: 'datetime',
              // format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "YYYY-MM-DD hh:mm:ss",
              search: false,
            },
            {
              label: "更新时间",
              prop: "updateTime",
              type: 'datetime',
              // format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "YYYY-MM-DD hh:mm:ss",
              search: false,
            }
          ]
        },
        data: [],
        uploadForm: {},
        enablePreview: false,
        previewPath: [],
        uploadOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              span: 24,
              // propsHttp: {
              //   res: 'data'
              // },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: baseUrl +  "/api-oss/info/upload"
            }
          ]
        }
      };
    },
    computed: {
      ...mapState(useUserStore, ["permission"]),
      permissionList() {
        return {
          addBtn: avueVaildData(this.permission.info_add, false),
          viewBtn: avueVaildData(this.permission.info_view, false),
          delBtn: avueVaildData(this.permission.info_delete, false),
          // editBtn: avueVaildData(this.permission.info_edit, false)
          editBtn: false   //文件不用编辑
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
          ossApi.add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
          ossApi.update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return ossApi.remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return ossApi.remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
            ossApi.getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      handleImport() {
        this.uploadBox = true;
      },
      uploadAfter(res, done, loading, column) {
        done();
        this.uploadBox = false;
        this.refreshChange();
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      preview(row) {
        this.enablePreview = true;
        let _imagePaths = [];
        _imagePaths.push(row.url);
        this.previewPath = _imagePaths;
      },
      closePreview() {
        this.enablePreview=false;
      },
      onLoad(page, params = {}) {
        this.loading = true;
          ossApi.getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.count;
          this.data = data.data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
